package com.ddstation.onsitelaw.controller;

import com.ddstation.onsitelaw.entity.AccountInEntity;
import com.ddstation.onsitelaw.entity.AccountSaveEntity;
import com.ddstation.onsitelaw.entity.DtInvsManageInstitutionEntity;
import com.ddstation.onsitelaw.entity.DtInvsManageInstitutionSupervisorEntity;
import com.ddstation.onsitelaw.model.AccountModel;
import com.ddstation.onsitelaw.service.AccountService;
import com.ddstation.onsitelaw.service.DtHealthManageInstitutionService;
import com.ddstation.onsitelaw.service.DtInvsManageInstitutionService;
import com.ddstation.onsitelaw.service.DtSupervisorEnforcementService;
import com.ddstation.onsitelaw.utils.MD5Util;
import com.ddstation.onsitelaw.utils.PageResult;
import com.ddstation.security.util.WnUserIdCrypt;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author 忆秋枫
 */
@Controller
public class AccountManageController {

    private static final Logger logger = LoggerFactory.getLogger(AccountManageController.class);

    @Inject
    private AccountService accountService;
    @Inject
    private DtInvsManageInstitutionService invsManageInstitutionService;
    @Inject
    private DtHealthManageInstitutionService healthManageInstitutionService;
    @Inject
    private DtSupervisorEnforcementService supervisorEnforcementService;
    @Inject
    private DtInvsManageInstitutionService dtInvsManageInstitutionService;

    /**
     * 跳转账号管理页
     */
    @RequestMapping(value = "accountManage")
    String accountManage(HttpSession session, Model model) {
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            //session无登录信息返回登录页
            model.addAttribute("code", -1);
            model.addAttribute("msg", "登录状态已失效，请重新登录!");
            return "accountManage";
        }
        model.addAttribute("county", account.getManageInstitutionEntity().getCounty());
        return "accountManage";
    }


    @RequestMapping("accountManage.do/list")
    @ResponseBody
    Map<String, Object> accountList(
            HttpSession session,
            @RequestBody AccountInEntity inEntity) {
        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        try {
            //获取session登录信息
            AccountModel account = (AccountModel) session.getAttribute("account");
            if (account == null || account.getSupervisorId() == null) {
                map.put("errCode", -1);
                return map;
            }
            //校验参数
            if (inEntity.getUserName() == null || "".equals(inEntity.getUserName())) {
                inEntity.setUserName(null);
            }

            DtInvsManageInstitutionEntity manageInstitutionEntity = account.getManageInstitutionEntity();
            if (manageInstitutionEntity.getProvince() == null || manageInstitutionEntity.getCity() == null) {
                //区域信息不完整
                map.put("errMsg", "当前账户所属区域信息不完整!");
                return map;
            }
            HashMap paramMap = new HashMap();
            paramMap.put("pageNum", inEntity.getPageNum());
            paramMap.put("pageSize", inEntity.getPageSize());
            paramMap.put("userName", inEntity.getUserName());
            paramMap.put("institutionId", account.getInstitutionId());
            //区管理员 显示 区监察员(所有)
            PageResult pageResult = null;
            if (!StringUtils.isEmpty(account.getManageInstitutionEntity().getCounty())) {
                pageResult = accountService.selectSupervisors(paramMap);
            }

            /*市管理员 显示 区管理员和市监察员*/
            if (StringUtils.isEmpty(account.getManageInstitutionEntity().getCounty())) {
                paramMap.put("province", account.getManageInstitutionEntity().getProvince());
                paramMap.put("city", account.getManageInstitutionEntity().getCity());
                pageResult = accountService.selectManagerAndSupervisors(paramMap);
            }
            //返回数据
            map.put("dataInfo", pageResult.getRows());
            map.put("allPage", pageResult.getTotal());
            map.put("pages", pageResult.getPages());
            //请求成功
            map.put("errCode", 1);
            map.put("errMsg", "请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询账户列表异常" + e.getMessage());
        }
        return map;
    }


    @RequestMapping("accountManage.do/delete")
    @ResponseBody
    Map<String, Object> accountDelete(
            @RequestParam Integer supervisorId,//账号ID
            HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        try {
            //获取session登录信息
            AccountModel account = (AccountModel) session.getAttribute("account");
            if (account == null || account.getSupervisorId() == null) {
                map.put("errCode", -1);
                return map;
            }
            //查询账号信息
            AccountModel accountModel = accountService.selectById(supervisorId);
            if (accountModel == null) {
                map.put("errMsg", "登录账号不存在或已删除。");
                return map;
            }
            //判断是否为当前账号
            if (account.getSupervisorId().equals(accountModel.getSupervisorId())) {
                map.put("errMsg", "不能对当前账户进行操作。");
                return map;
            }
            //判断删除账号是否为管理员
            if (accountModel.getRoleId() == 1) {
                //是管理员则判断当前账户是否为市管理员(身份为管理员且不是区管理员)
                if (!(account.getRoleId() == 1 && account.getManageInstitutionEntity().getCounty() == null)) {
                    map.put("errMsg", "无操作权限。");
                    return map;
                }
            } else {
                //非管理员则判断是否为所属上级(区域ID需一致)
                if (!account.getInstitutionId().equals(accountModel.getInstitutionId())) {
                    map.put("errMsg", "无操作权限。");
                    return map;
                }
            }
            //删除账号
            accountService.deleteById(supervisorId);
            //请求成功
            map.put("errCode", 1);
            map.put("errMsg", "请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("账户添加/修改异常" + e.getMessage());
        }
        return map;
    }

    @RequestMapping("accountManage.do/resetPassword")
    @ResponseBody
    Map<String, Object> accountResetPassword(
            @RequestParam Integer supervisorId,//账号ID
            HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        try {
            //获取session登录信息
            AccountModel account = (AccountModel) session.getAttribute("account");
            if (account == null || account.getSupervisorId() == null) {
                map.put("errCode", -1);
                return map;
            }
            //查询账号信息
            AccountModel accountModel = accountService.selectById(supervisorId);
            if (accountModel == null) {
                map.put("errMsg", "登录账号不存在或已删除。");
                return map;
            }
            //判断是否为当前账号
            if (account.getSupervisorId().equals(accountModel.getSupervisorId())) {
                map.put("errMsg", "不能对当前账户进行操作。");
                return map;
            }
            //判断重置账号是否为管理员
            if (accountModel.getRoleId() == 1) {
                //是管理员则判断当前账户是否为市管理员(身份为管理员且不是区管理员)
                if (!(account.getRoleId() == 1 && account.getManageInstitutionEntity().getCounty() == null)) {
                    map.put("errMsg", "无操作权限。");
                    return map;
                }
            } else {
                //非管理员则判断是否为所属上级(区域ID需一致)
                if (!account.getInstitutionId().equals(accountModel.getInstitutionId())) {
                    map.put("errMsg", "无操作权限。");
                    return map;
                }
            }
            //重置密码
            String password = "123456";
            accountService.updatePassword(supervisorId, MD5Util.md5Encode(password));
            //请求成功
            map.put("errCode", 1);
            map.put("errMsg", "请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("账户添加/修改异常" + e.getMessage());
        }
        return map;
    }

    @RequestMapping("accountManage.do/getRegion")
    @ResponseBody
    Map<String, Object> accountGetRegion(
            HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        try {
            //获取session登录信息
            AccountModel account = (AccountModel) session.getAttribute("account");
            if (account == null || account.getSupervisorId() == null) {
                map.put("errCode", -1);
                return map;
            }
            //获取数据
            DtInvsManageInstitutionEntity entity = account.getManageInstitutionEntity();
            List<DtInvsManageInstitutionEntity> regionList = invsManageInstitutionService
                    .selectByAddress(entity.getProvince(), entity.getCity(), entity.getCounty());
            map.put("regionList", regionList);
            //请求成功
            map.put("errCode", 1);
            map.put("errMsg", "请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("账户添加/修改异常" + e.getMessage());
        }
        return map;
    }

    @RequestMapping("accountManage.do/getInstitution")
    @ResponseBody
    Map<String, Object> accountGetInstitution(
            HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        try {
            //获取session登录信息
            AccountModel account = (AccountModel) session.getAttribute("account");
            if (account == null || account.getSupervisorId() == null) {
                map.put("errCode", -1);
                return map;
            }
            //获取数据
            DtInvsManageInstitutionEntity entity = account.getManageInstitutionEntity();
            List<Map<String, Object>> institutionList = healthManageInstitutionService
                    .selectByAddress(entity.getProvince(), entity.getCity(), entity.getCounty());
            map.put("institutionList", institutionList);
            //请求成功
            map.put("errCode", 1);
            map.put("errMsg", "请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("账户添加/修改异常" + e.getMessage());
        }
        return map;
    }

    @RequestMapping("accountManage.do/saveAccount")
    @ResponseBody
    Map<String, Object> saveAccount(
            HttpSession session,
            @RequestBody AccountSaveEntity saveEntity) {
        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        try {
            //获取session登录信息
            AccountModel account = (AccountModel) session.getAttribute("account");
            if (account == null || account.getSupervisorId() == null) {
                map.put("errCode", -1);
                return map;
            }
            //参数校验
            if (StringUtils.isEmpty(saveEntity.getLoginUser()) || StringUtils.isEmpty(saveEntity.getLoginPassword())
                    || StringUtils.isEmpty(saveEntity.getName()) || StringUtils.isEmpty(saveEntity.getPhone())) {
                map.put("errMsg", "参数不能为空");
                return map;
            }
            if (saveEntity.getLoginUser().length() < 4 || saveEntity.getLoginUser().length() > 16) {
                map.put("errMsg", "请输入4-16位账号名称");
                return map;
            }
            if (saveEntity.getLoginPassword().length() < 6 || saveEntity.getLoginPassword().length() > 16) {
                map.put("errMsg", "请输入6-16位账号密码");
                return map;
            }
            if (saveEntity.getName().length() < 2 || saveEntity.getName().length() > 16) {
                map.put("errMsg", "请输入2-16位用户姓名");
                return map;
            }
            if (saveEntity.getPhone().length() != 11) {
                map.put("errMsg", "请输入11位用户手机");
                return map;
            }
            //身份
            if (saveEntity.getRoleId() == 1) {
                //管理员 获取监管区域
                if (StringUtils.isEmpty(saveEntity.getInstitutionId())) {
                    map.put("errMsg", "监管区域不正确");
                    return map;
                }
            } else {
                //监督员 获取监管机构集合
                if (saveEntity.getInstitutionList() == null || saveEntity.getInstitutionList().size() == 0) {
                    map.put("errMsg", "请添加监管机构");
                    return map;
                }
                //监督员所属区域ID为当前添加的管理员区域ID
                saveEntity.setInstitutionId(account.getInstitutionId());
            }
            //查询账户名称身份存在
            AccountModel accountModel = accountService.selectByLoginUser(saveEntity.getLoginUser());
            if (accountModel != null) {
                map.put("errMsg", "账号名称已存在");
                return map;
            }
            //添加账号
            accountService.saveSupervisor(saveEntity);
            if (saveEntity.getId() != null) {
                //添加更多账号信息
                saveEntity.setLoginPassword(MD5Util.md5Encode(saveEntity.getLoginPassword()));
                accountService.saveInstitutionSupervisor(saveEntity);
                if (saveEntity.getRoleId() != 1) {
                    //如果是监督员 添加监督机构
                    supervisorEnforcementService.saveEnforcement(saveEntity);
                }
            }
            //请求成功
            map.put("errCode", 1);
            map.put("errMsg", "请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("账户添加/修改异常" + e.getMessage());
        }
        return map;
    }

    @RequestMapping("accountManage.do/updateAccount")
    @ResponseBody
    Map<String, Object> updateAccount(
            HttpSession session,
            @RequestBody AccountSaveEntity saveEntity) {
        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        try {
            //获取session登录信息
            AccountModel account = (AccountModel) session.getAttribute("account");
            if (account == null || account.getSupervisorId() == null) {
                map.put("errCode", -1);
                return map;
            }
            //身份
            if (saveEntity.getRoleId() == 1) {
                //管理员 获取监管区域
                if (StringUtils.isEmpty(saveEntity.getInstitutionId())) {
                    map.put("errMsg", "监管区域不正确");
                    return map;
                }
                //修改监管区域
                accountService.updateInstitutionId(saveEntity.getId(), saveEntity.getInstitutionId());
            } else {
                //监督员 获取监管机构集合
                if (saveEntity.getInstitutionList() == null || saveEntity.getInstitutionList().size() == 0) {
                    map.put("errMsg", "请添加监管机构");
                    return map;
                }
                //删除当前机构机构
                supervisorEnforcementService.deleteEnforcement(saveEntity.getId());
                //添加新的监管机构
                supervisorEnforcementService.saveEnforcement(saveEntity);
            }
            //请求成功
            map.put("errCode", 1);
            map.put("errMsg", "请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("账户添加/修改异常" + e.getMessage());
        }
        return map;
    }

    @RequestMapping("accountManage.do/getJurisdictionInstitution")
    @ResponseBody
    Map<String, Object> getJurisdictionInstitution(
            @RequestParam Integer supervisorId,//账号ID
            HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        try {
            //获取session登录信息
            AccountModel account = (AccountModel) session.getAttribute("account");
            if (account == null || account.getSupervisorId() == null) {
                map.put("errCode", -1);
                return map;
            }
            //查询账号拥有权限机构
            List<Map<String, Object>> enforcementList = supervisorEnforcementService.selectMoreBySupervisorId(supervisorId);
            if (enforcementList == null) {
                enforcementList = new ArrayList<>();
            }
            map.put("enforcementList", enforcementList);
            //请求成功
            map.put("errCode", 1);
            map.put("errMsg", "请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("账户添加/修改异常" + e.getMessage());
        }
        return map;
    }


    @RequestMapping("accountManage.do/bindAccount")
    @ResponseBody
    Map<String, Object> bindAccount(
            HttpSession session,
            @RequestParam Integer bindSupervisorId, String encryptUid) {
        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            map.put("errCode", -1);
            return map;
        }
        try {
            int uid = WnUserIdCrypt.decryptUid(encryptUid);
            DtInvsManageInstitutionSupervisorEntity entity = dtInvsManageInstitutionService.selectByWxUserId(uid);
            if (!ObjectUtils.isEmpty(entity)) {
                map.put("errCode", 0);
                map.put("errMsg", "此绑定码已经绑定:" + entity.getLoginUser());
                return map;
            }
            dtInvsManageInstitutionService.updateWxUserId(bindSupervisorId, uid);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("账户添加/修改异常" + e.getMessage());
            map.put("errCode", 0);
            map.put("errMsg", "非法的绑定码");
            return map;
        }
        //请求成功
        map.put("errCode", 1);
        map.put("errMsg", "请求成功");
        return map;
    }
}